//
//  BMAIntrusExoViewController.m
//  Autismus
//
//  Created by Nicolas CHENG on 03/12/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "BMAMovieViewController.h"
#import "BMAIntrusExoViewController.h"
#import "BMAIntruFactory.h"
#import "IntruExo.h"
#import "SoundManager.h"
#import "BMAGame.h"
#import "BMAAnswer.h"

@implementation BMAIntrusExoViewController

#define BUTTON_WIDTH        200
#define BUTTON_HEIGHT       200
#define BUTTON_MARGIN_X     50
#define BUTTON_MARGIN_Y     120
#define RIGHT_ANSWERS       5
#define WRONG_ANSWERS       8

@synthesize rightAnswers, wrongAnswers;
@synthesize factoryIntruExo;
@synthesize levelButton, currentLevel;
@synthesize expressionView, currentExercice, currentGameStat;

@synthesize congratsView;

-(id)init
{
    self = [super init];
    if (self)
    {
        // Init factory
        self.factoryIntruExo = [[BMAIntruFactory alloc] init];
        
        // Init level
        self.currentLevel = 1;
        self.rightAnswers = RIGHT_ANSWERS;
        self.wrongAnswers = WRONG_ANSWERS;
        
        UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
        button1.frame = CGRectMake(150, BUTTON_MARGIN_Y, BUTTON_WIDTH, BUTTON_HEIGHT);
        [button1 addTarget:self action:@selector(confirmAnswer:) forControlEvents:UIControlEventTouchDown];
        [button1 setTag:0];
        [self.view addSubview:button1];
        
        UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
        button2.frame = CGRectMake(150 + BUTTON_MARGIN_X + BUTTON_WIDTH, BUTTON_MARGIN_Y, BUTTON_WIDTH, BUTTON_HEIGHT);
        [button2 addTarget:self action:@selector(confirmAnswer:) forControlEvents:UIControlEventTouchDown];
        [button2 setTag:1];
        [self.view addSubview:button2];
        
        UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];
        button3.frame = CGRectMake(150 + (BUTTON_MARGIN_X * 2) + (BUTTON_WIDTH * 2), BUTTON_MARGIN_Y, BUTTON_WIDTH, BUTTON_HEIGHT);
        [button3 addTarget:self action:@selector(confirmAnswer:) forControlEvents:UIControlEventTouchDown];
        [button3 setTag:2];
        [self.view addSubview:button3];
        
        self.levelButton = [NSMutableArray arrayWithObjects:button1, button2, button3, nil];
        
        // Init Stat
        self.currentGameStat = [[BMAGame alloc] initEntity];
        self.currentGameStat.idGame = [NSNumber numberWithInt:1];
        self.currentGameStat.startDate = [NSDate date];
        
        // Next exercice
        [self nextExercice];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(IBAction)goBack:(id)sender
{
    // Save Stat
    self.currentGameStat.endDate = [NSDate date];
    [BMAGame saveContext];

    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Exercice

-(IBAction)confirmAnswer:(UIButton *)button
{
    bool res = [[[self.currentExercice.cardsArray objectAtIndex:button.tag] objectForKey:@"answer"] boolValue];
    
    BMAAnswer *answer = [[BMAAnswer alloc] initEntity];
    answer.startDate = self.currentExercice.creationdate;
    answer.endDate = [NSDate date];
    answer.level = [NSNumber numberWithInt:self.currentLevel];
    answer.value = [NSNumber numberWithBool:res];
    [self.currentGameStat addAnswersObject:answer];
    [BMAGame saveContext];

    if (res == TRUE)
    {        
        self.rightAnswers--;
        self.wrongAnswers = WRONG_ANSWERS;
        if (!self.rightAnswers)
        {
            self.rightAnswers = RIGHT_ANSWERS;
            [self nextLevel];
        }

        // Show Video and Play Sound
        BMAMovieViewController* theMoviePlayer = [[BMAMovieViewController alloc] initWithPath:[[NSBundle mainBundle] pathForResource:@"win" ofType:@"mp4"]];
        [self presentModalViewController:theMoviePlayer animated:NO];            
        theMoviePlayer.delegateIntru = self;
        // Play son
        [[SoundManager sharedManager] playMusic:@"son_bravo.aac" looping:NO];            

    }
    else
    {
        self.wrongAnswers--;
        self.rightAnswers = RIGHT_ANSWERS;
        if (!self.wrongAnswers)
        {
            self.wrongAnswers = WRONG_ANSWERS;
            [self previousLevel];
        }
    }
}

-(void)nextExercice
{
    // Get new exercice for cards
    self.currentExercice = [self.factoryIntruExo generateNewExerciceWithNbCards:[self.levelButton count]];
    
    // Add view to button
    for (int i = 0, end = [self.levelButton count]; i < end; ++i) {
        UIButton *tmpButton = [self.levelButton objectAtIndex:i];
        NSString *path = [[[self.currentExercice cardsArray] objectAtIndex:i] objectForKey:@"path"];
        [tmpButton setBackgroundImage:[UIImage imageNamed:path] forState:UIControlStateNormal];
    }
    
    // Add mascotte
    [self.expressionView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"mascotte_%@.png", self.currentExercice.illPathImg]]];
    
    // Play son
    [[SoundManager sharedManager] playMusic:[NSString stringWithFormat:@"son_%@.aac", self.currentExercice.illPathImg] looping:NO];
}

-(void)nextLevel
{
    if (self.currentLevel == 4)
        return ;
    self.currentLevel++;
    
    UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [newButton addTarget:self action:@selector(confirmAnswer:) forControlEvents:UIControlEventTouchDown];
    [newButton setTag:[self.levelButton count]];
    [self.view addSubview:newButton];
    [self.levelButton addObject:newButton];

    int x = 150;
    int y = BUTTON_MARGIN_Y;
    for (UIButton *tmp in self.levelButton)
    {
        tmp.frame = CGRectMake(x, y, BUTTON_WIDTH, BUTTON_HEIGHT);
        
        x += (BUTTON_WIDTH + BUTTON_MARGIN_X);
        if ((x + BUTTON_WIDTH + BUTTON_MARGIN_X) > 1024)
        {
            x = 150;
            y += BUTTON_HEIGHT + BUTTON_MARGIN_X;
        }
    }
}

-(void)previousLevel
{
    if (self.currentLevel == 1)
        return ;
    self.currentLevel--;
    UIButton *tmp = [self.levelButton lastObject];
    [tmp removeFromSuperview];
    [self.levelButton removeObject:tmp];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    congratsView.userInteractionEnabled = NO;
    congratsView.alpha = 0;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}

@end
